//
//  BGCollectionView.m
//  LittleCool
//
//  Created by 周博 on 17/3/13.
//  Copyright © 2017年 BogoZhou. All rights reserved.
//

#import "BGCollectionView.h"
#import "BGCollectionViewCell.h"
#import "ShopViewController.h"
#import "XYMScanViewController.h"
#import "UIImage+GIF.h"
#import "MapLocationViewController.h"
#import "ConnectWiFiViewController.h"
#import "WebViewController.h"
#import "LocalMapViewController.h"
#import "CurveListViewController.h"
#import "HistoryViewController.h"
#import <SystemConfiguration/CaptiveNetwork.h>


#define kCellName @"BGCollectionViewCell"

@interface BGCollectionView ()<UICollectionViewDelegate,UICollectionViewDataSource,UICollectionViewDelegateFlowLayout>
{
    
}

@end

@implementation BGCollectionView

- (instancetype)initWithFrame:(CGRect)frame withDataArray:(NSArray *)dataArray
{
    self = [super initWithFrame:frame];
    if (self) {
        _dataArray = dataArray;
        [self creatCollectionView];
    }
    return self;
}


- (void)creatCollectionView{
    UICollectionViewFlowLayout *floatLayout = [[UICollectionViewFlowLayout alloc] init];
    CGFloat width = (self.sizeWidth -15) /3;
//    CGFloat height= width * (262.0/340);
    CGFloat height= width;
    floatLayout.itemSize = CGSizeMake(width, height);//设置每个cell的大小
    floatLayout.sectionInset = UIEdgeInsetsMake(0, 2.5, 0, 2.5);//设置内容的内边距
    floatLayout.minimumInteritemSpacing = 0;//设置每个cell之间的最小间距
    floatLayout.scrollDirection = UICollectionViewScrollDirectionVertical;//设置滚动方向
    _collectionView = [[UICollectionView alloc] initWithFrame:CGRectMake(0, 0, self.sizeWidth, self.sizeHeight) collectionViewLayout:floatLayout];
    _collectionView.backgroundColor = kClearColor;
    _collectionView.delegate = self;
    _collectionView.dataSource = self;
    
    [_collectionView registerNib:[UINib nibWithNibName:kCellName bundle:nil] forCellWithReuseIdentifier:kCellName];
    [self addSubview:_collectionView];
}

- (void)reloadDataByArray:(NSMutableArray *)array{
    _dataArray = array;
    [_collectionView reloadData];
}

#pragma mark - collectionDataSource

- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView{
    return 1;
}

-(NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section{
    return _dataArray.count;
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath{
    BGCollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:kCellName forIndexPath:indexPath];
    MainListModel *model = _dataArray[indexPath.row];

    [cell showDataWithModel:model];
    if (model.code.integerValue == 107) {
        cell.label5Min.hidden = NO;
    }else if (model.code.integerValue == 104 || model.code.integerValue == 111 || model.code.integerValue == 103){
        cell.label5Min.text = @"WiFi设备专用";
        cell.label5Min.hidden = NO;
    }
    return cell;
}

- (CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout minimumLineSpacingForSectionAtIndex:(NSInteger)section{
    return 5;
}

- (CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout minimumInteritemSpacingForSectionAtIndex:(NSInteger)section{
    return 5;
}

- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath{    
    
    UIStoryboard *storyboard = kMainStroyboard;
    NSString *string = [NSString stringWithFormat:@"%ld",indexPath.row];
    
    MainListModel *model = _dataArray[indexPath.row];
    
    if (model.type.integerValue == 1) {//加载本地页面
        if (model.code.integerValue == 101) {//门店
            ShopViewController *shopVC = [storyboard instantiateViewControllerWithIdentifier:@"ShopViewController"];
            [[self findViewController:self].navigationController pushViewController:shopVC animated:YES];
            string = @"门店";
        }else if (model.code.integerValue == 102){//激活充电宝
            XYMScanViewController *scanView = [storyboard instantiateViewControllerWithIdentifier:@"XYMScanViewController"];
            scanView.type = @"102";
            scanView.contentString = model.small_prompt;
            [[self findViewController:self].navigationController pushViewController:scanView animated:YES];
            string = @"激活充电宝";
        }else if (model.code.integerValue == 103){//配置WiFi
//            ConnectWiFiViewController * connectWiFiVC = [storyboard instantiateViewControllerWithIdentifier:@"ConnectWiFiViewController"];
//            [[self findViewController:self].navigationController pushViewController:connectWiFiVC animated:YES];
            string = @"配置WiFi";
            [self wifi];
            
            
        }else if (model.code.integerValue == 104){//更新固件
            string = @"更新固件";
            
            XYMScanViewController *scanView = [storyboard instantiateViewControllerWithIdentifier:@"XYMScanViewController"];
            scanView.type = @"104";
            [[self findViewController:self].navigationController pushViewController:scanView animated:YES];
            
        }else if (model.code.integerValue == 105){//常见问题
            string = @"常见问题";
        }else if (model.code.integerValue == 106){//统计报表
            string = @"统计报表";
            
            HistoryViewController *curveVC = [storyboard instantiateViewControllerWithIdentifier:@"HistoryViewController"];
            [[self findViewController:self].navigationController pushViewController:curveVC animated:YES];
            
        }else if (model.code.integerValue == 107){//扫码充电
            string = @"扫码充电";
            XYMScanViewController *scanView = [storyboard instantiateViewControllerWithIdentifier:@"XYMScanViewController"];
            scanView.type = @"107";
            scanView.contentString = model.small_prompt;
            [[self findViewController:self].navigationController pushViewController:scanView animated:YES];
        }else if (model.code.integerValue == 108){//消息撤回
            string = @"消息撤回";
            XYMScanViewController *scanView = [storyboard instantiateViewControllerWithIdentifier:@"XYMScanViewController"];
            scanView.type = @"108";
            scanView.contentString = model.small_prompt;
            [[self findViewController:self].navigationController pushViewController:scanView animated:YES];
        }else if (model.code.integerValue == 109){//硬件故障
            string = @"硬件故障";
            XYMScanViewController *scanView = [storyboard instantiateViewControllerWithIdentifier:@"XYMScanViewController"];
            scanView.type = @"109";
            scanView.contentString = model.small_prompt;
            [[self findViewController:self].navigationController pushViewController:scanView animated:YES];
        }else if (model.code.integerValue == 110){//变更充电宝
            string = @"变更充电宝";
            XYMScanViewController *scanView = [storyboard instantiateViewControllerWithIdentifier:@"XYMScanViewController"];
            scanView.type = @"110";
            scanView.contentString = model.small_prompt;
            [[self findViewController:self].navigationController pushViewController:scanView animated:YES];
        }else if (model.code.integerValue == 111){
            XYMScanViewController *scanView = [storyboard instantiateViewControllerWithIdentifier:@"XYMScanViewController"];
            scanView.type = @"111";
            scanView.contentString = model.small_prompt;
            [[self findViewController:self].navigationController pushViewController:scanView animated:YES];
        }else if (model.code.integerValue == 112){//返厂
            XYMScanViewController *scanView = [storyboard instantiateViewControllerWithIdentifier:@"XYMScanViewController"];
            scanView.type = @"112";
            scanView.contentString = model.small_prompt;
            [[self findViewController:self].navigationController pushViewController:scanView animated:YES];
        }
    }else if (model.type.integerValue == 2){//打开url
        string = model.url;
        
        WebViewController *webView = [storyboard instantiateViewControllerWithIdentifier:@"WebViewController"];
        webView.titleString = model.name;
        webView.urlString = model.url;
        [[self findViewController:self].navigationController pushViewController:webView animated:YES];
        
    }
    
   
    
//    kAlert(string);

}

//获取当前WiFi名称
- (void)wifi{
    id info = nil;
    NSArray *ifs = (__bridge_transfer id)CNCopySupportedInterfaces();
    for (NSString *ifnam in ifs) {
        info = (__bridge_transfer id)CNCopyCurrentNetworkInfo((__bridge CFStringRef)ifnam);
        NSString *str = info[@"SSID"];
        //        NSString *str2 = info[@"BSSID"];
        //        NSString *str3 = [[ NSString alloc] initWithData:info[@"SSIDDATA"] encoding:NSUTF8StringEncoding];
        
        if ([str rangeOfString:@"ChongDianDian"].location ==NSNotFound || [BGFunctionHelper isNULLOfString:str]) {
            //包含
            [self alertVCByTitle:@"\t\t\t\t\t若要配置设备WiFi，点击‘确定’前去系统页面连接对应设备WiFi，连接上设备WiFi后回到APP会提示是否前去配置WiFi，点击确定后进行WiFi配置"];
        }else{
            UIStoryboard *storyboard = kMainStroyboard;
            WebViewController *webView = [storyboard instantiateViewControllerWithIdentifier:@"WebViewController"];
            webView.titleString = @"配置设备WiFi";
            webView.urlString = @"http://192.168.4.1/wifi_set.html";
            [[self findViewController:self].navigationController pushViewController:webView animated:YES];
        }
        
    }
}


- (void)alertVCByTitle:(NSString *)title{
    UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"配置方法" message:title preferredStyle:UIAlertControllerStyleAlert];
    
    NSMutableParagraphStyle *paragraphStyle = [[NSMutableParagraphStyle alloc] init];
    //paragraphStyle.lineBreakMode = NSLineBreakByWordWrapping;
    paragraphStyle.alignment = NSTextAlignmentLeft;
    //行间距
    paragraphStyle.lineSpacing = 5.0;
    NSDictionary * attributes = @{NSFontAttributeName : [UIFont systemFontOfSize:15.0], NSParagraphStyleAttributeName : paragraphStyle};
    NSMutableAttributedString *attributedTitle = [[NSMutableAttributedString alloc] initWithString:title];
    [attributedTitle addAttributes:attributes range:NSMakeRange(0, title.length)];
    // 下面这句话用了KVC ，将attributes的值给了alert
    [alert setValue:attributedTitle forKey:@"attributedMessage"];//attributedTitle\attributedMessage
    //end ---
    UIAlertAction *action = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
#define iOS10 ([[UIDevice currentDevice].systemVersion doubleValue] >= 10.0)
        NSString * urlString = @"App-Prefs:root=WIFI";
        if ([[UIApplication sharedApplication] canOpenURL:[NSURL URLWithString:urlString]]) {
            if (iOS10) {
                [[UIApplication sharedApplication] openURL:[NSURL URLWithString:urlString] options:@{} completionHandler:nil];
            } else {
                [[UIApplication sharedApplication] openURL:[NSURL URLWithString:@"prefs:root=WIFI"]];
            }
        }
    }];
    
    UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
        
    }];
    
    [alert addAction:cancelAction];
    [alert addAction:action];
    [[self findViewController:self] presentViewController:alert animated:YES completion:nil];
}


#pragma mark - 找到当前view所在的控制器
- (UIViewController *)findViewController:(UIView *)sourceView
{
    id target=sourceView;
    while (target) {
        target = ((UIResponder *)target).nextResponder;
        if ([target isKindOfClass:[UIViewController class]]) {
            break;
        }
    }
    return target;
}
/*
// Only override drawRect: if you perform custom drawing.
// An empty implementation adversely affects performance during animation.
- (void)drawRect:(CGRect)rect {
    // Drawing code
}
*/

@end
